<?php
include_once($_SERVER['DOCUMENT_ROOT']."/common/config.php");
$_conn = connect_mysql('bangumi');

include_once("./php/bilibili.php");

if(!preg_match('/^\d{1,6}$/', $_GET['spid'])){
	$error = "信息不全";
}else{
	$spid = $_GET['spid'];
	$sql = "SELECT spid, aid, cid, episode, title, cover, click, UNIX_TIMESTAMP(time) AS time FROM bangumi_sp_view WHERE spid = '$spid' ORDER BY episode DESC";
	$result2 = mysqli_query($_conn, $sql) or die("数据库错误");
	while($row = mysqli_fetch_assoc($result2)){
		if(time() - $row['time'] > 2 * 60 * 60){
			unset($bangumi_list);
			break;
		}
		$bangumi_list[] = array(
			'title' => urlencode($row['title']),
			'cover' => $row['cover'],
			'spid' => $row['spid'],
			'click' => $row['click'],
			'aid' => $row['aid'],
			'cid' => $row['cid'],
			'episode' => $row['episode']
		);
	}
		
	if(!isset($bangumi_list)){
		$params = array(
			'spid' => $spid,
			'bangumi' => 1
		);	
		$result2 = get_bilibili('spview', $params);
		$list = json_decode($result2);
		if($list && $list->code == '0' && count($list->list)){
			foreach($list->list as $row){
				$bangumi_list[] = array(
					'title' => urlencode($row->title),
					'cover' => $row->cover,
					'spid' => $spid,
					'click' => $row->click,
					'aid' => $row->aid,
					'cid' => $row->cid,
					'episode' => $row->episode,
				);
				$sql1 = "INSERT INTO bangumi_sp_view (spid, aid, cid, episode, title, cover, click, time) SELECT '{$spid}', '{$row->aid}', '{$row->cid}', '{$row->episode}', '{$row->title}', '{$row->cover}', '{$row->click}', NOW() FROM dual WHERE NOT EXISTS (SELECT * FROM bangumi_sp_view WHERE bangumi_sp_view.aid = '{$row->aid}');";
				mysqli_query($_conn, $sql1) or die(mysqli_error($_conn));	
			}
			$sql2 = "UPDATE bangumi_sp_view SET time = NOW() WHERE spid = '$spid'";
			mysqli_query($_conn, $sql2) or die(mysqli_error($_conn));
		}else{
			$error = "获取数据失败";
		}
	}
}

$error = isset($error) ? $error : null;

$data = array(
	'error' => urlencode($error),
	'list' => $bangumi_list
);
//echo urldecode(stripslashes(json_encode($data)));

$sp_view = urldecode(stripslashes(json_encode($data)));